//
//  FormalRegisterViewController.m
//  LoanOne
//
//  Created by WangZhenyu on 2017/10/16.
//  Copyright © 2017年 WangZhenyu. All rights reserved.
//

#import "FormalRegisterViewController.h"
#import "GlobalFunction.h"
#import "WebShowViewController.h"

@interface FormalRegisterViewController (){
    NSTimer     *timer;
    NSInteger   count;
    BOOL        phoneInputBool;
    BOOL        codeInputBool;
    BOOL        onePasswordInputBool;
    BOOL        twoPasswordInputBool;
}
@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;
@property (weak, nonatomic) IBOutlet UITextField *codeTextField;
@property (weak, nonatomic) IBOutlet UIButton *codeBtn;
@property (weak, nonatomic) IBOutlet UIButton *sureBtn;
@property (weak, nonatomic) IBOutlet UITextField *onePasswordTextFiled;
@property (weak, nonatomic) IBOutlet UITextField *twoPasswordTextFiled;
@property (weak, nonatomic) IBOutlet UIView *bottomView;

@end

@implementation FormalRegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addBackBtn];
    
    [self.codeBtn setBackgroundImage:getColorToImage(RGB(107, 118, 233)) forState:UIControlStateNormal];
    [self.sureBtn setBackgroundImage:getColorToImage(RGB(107, 118, 233)) forState:UIControlStateNormal];
    
    self.sureBtn.enabled = NO;
    self.codeBtn.enabled = NO;
    self.codeBtn.layer.masksToBounds = YES;
    self.codeBtn.layer.cornerRadius = 5.0f;
    
    phoneInputBool = NO;
    codeInputBool = NO;
    onePasswordInputBool = NO;
    twoPasswordInputBool = NO;
    
    if (self.type == RegisterType_change) {
        self.title = @"修改密码";
        self.phoneTextField.text = [DEFAULTS objectForKey:USERID];
        [self.sureBtn setTitle:@"确定修改" forState:UIControlStateNormal];
        phoneInputBool = YES;
        self.phoneTextField.enabled = NO;
        self.codeBtn.enabled = YES;
        self.codeBtn.userInteractionEnabled = YES;
    }else if (self.type == RegisterType_forgot){
        self.title = @"忘记密码";
        [self.sureBtn setTitle:@"确定修改" forState:UIControlStateNormal];
    }else{
        self.bottomView.hidden = NO;
        self.title = @"注册";
        [self.sureBtn setTitle:@"同意协议并注册" forState:UIControlStateNormal];
    }
    
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)codePress {
    [self.codeBtn setTitle:@"正在获取" forState:UIControlStateNormal];
    self.codeBtn.userInteractionEnabled = NO;
    
    if (self.type == RegisterType_default) {
        NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
        [dic setObject:self.phoneTextField.text forKey:@"mobileNumber"];
        [[ServiceRequest sharedService] GET:@"user/existence" parameters:dic success:^(id responseObject) {
            NSLog(@"aa");
            self.codeBtn.userInteractionEnabled = YES;
            [self showHUDAlert:@"手机号已经被注册"];
            [self.codeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        } failure:^(NSString *error, NSInteger code) {
            if (code == 404) {
                [self getPhoneCode];
            }else if (code == 409) {
                self.codeBtn.userInteractionEnabled = YES;
                [self showHUDAlert:@"手机号已经被注册"];
                [self.codeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
            }else{
                self.codeBtn.userInteractionEnabled = YES;
                [self showHUDAlert:error];
                [self.codeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
            }
        }];
    }else if (self.type == RegisterType_forgot){
        NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
        [dic setObject:self.phoneTextField.text forKey:@"mobileNumber"];
        [[ServiceRequest sharedService] GET:@"user/existence" parameters:dic success:^(id responseObject) {
            NSLog(@"aa");
            [self getPhoneCode];
        } failure:^(NSString *error, NSInteger code) {
            if (code == 404) {
                [self showHUDAlert:@"该手机号未被注册"];
                self.codeBtn.userInteractionEnabled = YES;
                [self.codeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
            }else if (code == 409) {
                [self getPhoneCode];
            }else{
                self.codeBtn.userInteractionEnabled = YES;
                [self showHUDAlert:error];
                [self.codeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
            }
        }];
    }else{
        [self getPhoneCode];
    }
}

- (void)getPhoneCode{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setObject:self.phoneTextField.text forKey:@"mobileNumber"];
    [dic setObject:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"] forKey:@"appName"];
    [[ServiceRequest sharedService] GET:@"sms/yunpian/code" parameters:dic success:^(id responseObject) {
        count = 60;
        if (timer) {
            [timer invalidate];
            timer = nil;
        }
        timer = [NSTimer scheduledTimerWithTimeInterval:1
                                                 target:self
                                               selector:@selector(updateTime)
                                               userInfo:nil
                                                repeats:YES];
    } failure:^(NSString *error, NSInteger code) {
        [self showHUDAlert:error];
        [self.codeBtn setTitle:@"重新发送" forState:UIControlStateNormal];
        self.codeBtn.userInteractionEnabled = YES;
    }];
}

- (IBAction)surePress {
    if (self.onePasswordTextFiled.text.length < 6 || self.twoPasswordTextFiled.text.length < 6) {
        [self showHUDAlert:@"密码至少输入6位数"];
        return;
    }
    if (![self.onePasswordTextFiled.text isEqualToString:self.twoPasswordTextFiled.text]) {
        [self showHUDAlert:@"密码输入不一致"];
        return;
    }
    [self loadingHUDAlert:@"正在处理"];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setObject:self.phoneTextField.text forKey:@"mobileNumber"];
    [dic setObject:self.codeTextField.text forKey:@"verifyCode"];
    [[ServiceRequest sharedService] GET:@"sms/validation" parameters:dic success:^(id responseObject) {
        [self nextAction];
    } failure:^(NSString *error, NSInteger code) {
        [self hideHudAlert];
        [self showHUDAlert:error];
    }];
}

- (void)nextAction{
    count = 60;
    if (timer) {
        [timer invalidate];
        timer = nil;
    }
    [self.codeBtn setTitle:@"重新发送" forState:UIControlStateNormal];
    self.codeBtn.userInteractionEnabled = YES;
    
    if (self.type == RegisterType_default) {
        NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
        [dic setObject:self.phoneTextField.text forKey:@"mobileNumber"];
        [dic setObject:self.onePasswordTextFiled.text forKey:@"password"];
        [dic setObject:@"" forKey:@"name"];
        [[ServiceRequest sharedService] POSTJSON:@"user" parameters:dic success:^(id responseObject) {
            [self hideHudAlert];
            [self showHUDAlert:@"注册成功"];
            if (self.RefreshPhone) {
                self.RefreshPhone(self.phoneTextField.text);
            }
            if (self.RefreshHandle) {
                self.RefreshHandle();
            }
            [self performSelector:@selector(goBackAction) withObject:self afterDelay:2.0f];
        } failure:^(NSString *error, NSInteger code) {
            if (code == 409) {
                [self showHUDAlert:@"您注册的用户已存在"];
            }else{
                [self showHUDAlert:error];
            }
        }];
    }else{
        NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
        [dic setObject:self.phoneTextField.text forKey:@"mobileNumber"];
        [dic setObject:self.onePasswordTextFiled.text forKey:@"newPassword"];
        [[ServiceRequest sharedService] POST:@"user/password" parameters:dic success:^(id responseObject) {
            [self hideHudAlert];
            [self showHUDAlert:@"修改密码成功"];
            if (self.RefreshHandle) {
                self.RefreshHandle();
            }
            [self performSelector:@selector(goBackAction) withObject:self afterDelay:2.0f];
        } failure:^(NSString *error, NSInteger code) {
            if (self.type == RegisterType_forgot) {
                if (code == 404 || code == 400) {
                    [self showHUDAlert:@"当前用户不存在"];
                }else{
                    [self showHUDAlert:error];
                }
            }else if (self.type == RegisterType_change){
                [self showHUDAlert:error];
            }else{
                [self showHUDAlert:error];
            }
            
        }];
    }
    
}


#pragma mark 更新时间
-(void)updateTime
{
    count--;
    if (count > 0) {
        [self.codeBtn setTitle:[NSString stringWithFormat:@"已发送(%ld)",(long)count] forState:UIControlStateNormal];
        self.codeBtn.userInteractionEnabled = NO;
        return;
    }
    else{
        self.codeBtn.userInteractionEnabled = YES;
        [self.codeBtn setTitle:@"重新发送" forState:UIControlStateNormal];
        [timer invalidate];
        timer = nil;
    }
}


#pragma mark---uitextfieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (textField == self.phoneTextField) {
        if ([textField.text stringByReplacingCharactersInRange:range withString:string].length == 11) {
            self.codeBtn.enabled = YES;
            phoneInputBool = YES;
        }else if([textField.text stringByReplacingCharactersInRange:range withString:string].length > 11){
            return NO;
        }else{
            self.codeBtn.enabled = NO;
            phoneInputBool = NO;
        }
    }else if (textField == self.codeTextField){
        if ([textField.text stringByReplacingCharactersInRange:range withString:string].length > 0) {
            codeInputBool = YES;
        }else{
            codeInputBool = NO;
        }
    }else if (textField == self.onePasswordTextFiled){
        if ([textField.text stringByReplacingCharactersInRange:range withString:string].length > 0) {
            onePasswordInputBool = YES;
        }else{
            onePasswordInputBool = NO;
        }
    }else if (textField == self.twoPasswordTextFiled){
        if ([textField.text stringByReplacingCharactersInRange:range withString:string].length > 0) {
            twoPasswordInputBool = YES;
        }else{
            twoPasswordInputBool = NO;
        }
    }
    [self setVerificationCodeBtnClick];
    return YES;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField{
    if (textField == self.phoneTextField) {
        self.codeBtn.enabled = NO;
        phoneInputBool = NO;
        [self.codeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    }
    self.sureBtn.enabled = NO;
    return YES;
}

- (void)setVerificationCodeBtnClick{
    if (phoneInputBool && codeInputBool && onePasswordInputBool && twoPasswordInputBool) {
        self.sureBtn.enabled = YES;
    }else{
        self.sureBtn.enabled = NO;
    }
}

- (IBAction)showServerProtocolPress {
    WebShowViewController *viewCon = [[WebShowViewController alloc] initWithNibName:@"WebShowViewController" bundle:nil];
    viewCon.urlStr = [NSString stringWithFormat:@"%@bawangdai/serverProtocol.html", HOSTURL];
    [self.navigationController pushViewController:viewCon animated:YES];
}


@end
